package com.example.file.controller;

import com.example.common.result.PageResult;
import com.example.file.entity.query.FileQuery;
import com.example.file.entity.vo.SysFileVo;
import com.example.file.service.FileService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;

@RestController
@RequestMapping("file")
@Validated
public class FileController {
    @Resource
    private FileService fileService;

    /**
     * 上传文件
     *
     * @param file
     */
    @PostMapping
    public SysFileVo insertFile(@NotNull(message = "文件不能为空") MultipartFile file) {
        SysFileVo sysFileVo = fileService.insertFile(file);
        return sysFileVo;
    }

    /**
     * 删除文件
     *
     * @param fileId
     */
    @DeleteMapping("/{fileId}")
    public String deleteFileById(@PathVariable("fileId") Long fileId) {
        fileService.deleteFileById(fileId);
        return "success";
    }

    /**
     * 查询文件详细信息
     *
     * @param fileId
     */
    @GetMapping("/{fileId}")
    public SysFileVo selectFileInfoByFileId(@PathVariable("fileId") Long fileId) {
        return fileService.selectFileInfoByFileId(fileId);
    }

    /**
     * 查询文件列表
     * @param fileQuery
     * @return
     */
    @GetMapping("file-list")
    public PageResult selectFileInfoList(FileQuery fileQuery) {
        return fileService.selectFileInfoList(fileQuery);
    }

    /**
     * 根据文件id下载文件
     * @param fileId
     */
    @GetMapping("/download/{fileId}")
    public void downloadFileByFileId(@PathVariable("fileId") Long fileId, HttpServletResponse resp) throws IOException {
        fileService.selectFileBinary(fileId,resp);
    }
}